// 这份代码专门处理逻辑层的操作
const axios = require('axios');

const userDao = require('../dao/userDao');
const powerDao = require('../dao/powerDao');

// 获取微信小程序配置信息
const { wx } = require('../util/server_config');
const { appid, secret } = wx;

// 引入jwt
const { createUserJwtToken, verifyJwtToken } = require('../util/server_jwt');

const userService = {
    /*
     * 无感登录接口
     */
    async wxLoginBycode(code) {
        // 向微信服务器发请求获取用户信息
        let data;
        try {
            const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
                params: {
                    appid: appid,
                    secret: secret,
                    js_code: code,
                    grant_type: 'authorization_code'
                }
            });
            data = response.data;
            if (data.errcode) {
                return { success: false, err: data.errmsg, code: data.errcode };
            }
        } catch (error) {
            console.log(error);
            return { success: false, err: '服务器错误' };
        }
        // 获取openid
        let openid = data.openid;
        // 验证登录
        let result;
        try {
            let tmp = await userDao.loginByOpenid(openid);
            if (tmp.length == 0) {
                tmp = await userDao.addUser(openid);
            }
            if (tmp[0].allowLogin == 'true') {
                // 生成jwt令牌
                let payload1 = {uid: tmp[0].id, username: tmp[0].username, userType: tmp[0].userType};
                let payload2 = {uid: tmp[0].id, username: tmp[0].username, userType: tmp[0].userType};
                // 将 jwt令牌 的有效时间设置为 20小时
                let loginToken = await createUserJwtToken(payload1, {expiresIn: '168h'});
                let powerToken = await createUserJwtToken(payload2, {expiresIn: '20h'});
                // 返回数据
                result = {
                    success: true,
                    msg: "登录成功",
                    data: {
                        loginToken,
                        powerToken,
                        uid: tmp[0].id,
                        userType: tmp[0].userType,
                        username: tmp[0].username
                    }
                };
            } else {
                result = { success: false, msg: "该账号已被冻结，请联系管理员" };
            }
        } catch (err) {
            result = {success: false, msg: "数据库异常"};
        }
        return result;
    },
    /*
     * 验证 token
     */
    async checkUserLoginByJwt(loginToken, powerToken) {
        try {
            let powerTokenData = await verifyJwtToken(powerToken);
            return { success: true, msg: "登录成功", data: { login: true } };
        } catch (err) {
            if (err.code == 1) {
                // 这里需要验证 loginToken 是否过期并且颁布新的token
                ;
                return { success: true, msg: "token 已过期", data: { login: false } };
            } else {
                return { success: true, msg: "token 已过期", data: { login: false } };
            }
        }
    },
    // /*
    //  * 查询用户是否存在
    //  */
    // async checkUserExistByOpenid(openid) {
    //     let result = await userLibrary.checkUserExistByOpenid({openid: openid});
    //     if (result.result) {
    //         return {result: true, uid: result.uid};
    //     }
    //     return {result: false};
    // },
    
    // /*
    //  * 添加用户
    //  */
    // async addUser(user) {
    //     let result = await userLibrary.addUser(user);
    //     if (result.result) {
    //         return {success: true, uid: result.result.insertId};
    //     }
    //     return {success: false};
    // },
    // /*
    //  * 手机号密码登录
    //  */
    // async loginByPhone(loginData) {
    //     let result = await userLibrary.selectUserByPhoneAndPassWord(loginData);
    //     if (result.success) {
    //         return {result: true, userInfo: result.userInfo};
    //     }
    //     return {result: false};
    // },
    /*
     * 根据uid查询用户信息
     */
    async getUserInfoByUid(uid) {
        let result;
        try {
            result = await userDao.getUserInfoByUid(uid);
            if (result.length == 0) {
                result = { success: false, msg: '用户不存在' };
            } else {
                result = { success: true, msg: '获取用户信息成功', data: result[0] };
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    /*
     * 更新用户个人信息
     */
    async setUserInfo(uid, userIconId, username, phone, bio) {
        let result;
        try {
            result = await userDao.setUserInfo(uid, userIconId, username, phone, bio);
            if (result.affectedRows == 0) {
                result = { success: false, msg: '更新用户信息失败' };
            } else {
                result = { success: true, msg: '更新用户信息成功' };
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    // 账号密码登录
    async adminLogin(username, password) {
        let result;
        try {
            result = await userDao.adminLogin(username, password);
            if (result.length == 0) {
                result = { success: false, msg: '用户名或密码错误' };
            } else {
                let jwt = await createUserJwtToken({uid: result[0].uid, username: result[0].username, userType: result[0].userType}, {expiresIn: '20h'});
                result = { success: true, msg: '登录成功', token: jwt, userType: result[0].userType };
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    async getAllUser(uid, page) {
        let result;
        // 鉴权
        try {
            let power = await powerDao.checkPower(uid, '用户管理');
            if (power.length == 0) {
                result = { success: false, msg: '权限不足' };
                return result;
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
            return result;
        }
        // 业务逻辑
        try {
            let data = await userDao.getAllUser(page);
            result = { success: true, msg: '获取所有用户成功', data };
        } catch (err) {
            result = { success: false, msg: '数据库异常' };
        }
        return result;
    }
};

module.exports = userService;
